package com.yc.config;

import com.yc.config.handler.CustomAccessDeniedHandler;
import com.yc.config.handler.CustomAuthExceptionEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;


@Configuration
@EnableResourceServer
public class ResouceServerConfig extends
        ResourceServerConfigurerAdapter {



    public static final String RESOURCE_ID = "res1";

    @Autowired
    TokenStore tokenStore;

    /**
     * 自定义访问无权限资源时的异常
     */
    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;

    /**
     * 自定义认证失败的异常
     */
    @Autowired
    private CustomAuthExceptionEntryPoint exceptionEntryPoint;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {

        resources
                //必须拥有RESOURCE_ID 配置, 如果不使用克注释掉
                .resourceId(RESOURCE_ID)
                //使用自己配置的令牌服务
                .tokenStore(  tokenStore)
                //   自定义认证失败的异常 自定义访问无权限资源时的异常
                .authenticationEntryPoint(exceptionEntryPoint).accessDeniedHandler(accessDeniedHandler)
                .stateless(true);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        /**
         * 拦截所有请求,同时scopes必须使用all的     如果不需要可以使用下面的注释掉,或者使用下面的认证配置
         *   .antMatchers("/**").access("#oauth2.hasScope('all')")
         */
        http
                .authorizeRequests()
                .antMatchers("/**")
                .access("#oauth2.hasScope('all')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        /**
         *
         */
        // 所有请求必须认证通过
//        http.authorizeRequests()
//                // 过滤放行
//                .antMatchers().permitAll()
//                .anyRequest().authenticated();
    }

}
